package org.pine.common.beans;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.pine.api.enums.ResultCodeEnum;

import java.io.Serial;
import java.io.Serializable;

/**
 * 接口响应结果
 *
 * @author pine
 * @version 1.0
 * @since 2025-04-10 17:52
 */
@Data
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@Schema(description = "接口响应结果")
@JsonPropertyOrder({"code", "message", "data", "logId", "timestamp"})
public class Result<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 9102134480080512751L;

    @JsonProperty(index = 1, value = "code")
    private Integer code;

    @JsonProperty(index = 2, value = "message")
    private String message;

    @JsonProperty(index = 3, value = "data")
    private T data;

    @JsonProperty(index = 4, value = "logId")
    private String logId;

    @JsonProperty(index = 5, value = "timestamp")
    private Long timestamp;


    public Result() {
        this(ResultCodeEnum.SUCCESS);
    }

    public Result(T data) {
        this(ResultCodeEnum.SUCCESS, data);
    }

    public Result(@NotNull ResultCodeEnum resultCode) {
        this(resultCode, null);
    }

    public Result(@NotNull ResultCodeEnum resultCode, T data) {
        this(resultCode.getCode(), resultCode.getDesc(), data);
    }

    public Result(Integer code, String desc, T data) {
        this.code = code;
        this.message = desc;
        this.data = data;
        this.logId = LogId.get();
        this.timestamp = System.currentTimeMillis();
    }

    public static <T> Result<T> success() {
        return new Result<>();
    }

    public static <T> Result<T> success(T data) {
        return new Result<>(data);
    }

    public static <T> Result<T> error(@NotNull ResultCodeEnum resultCode) {
        return new Result<>(resultCode);
    }

    public static <T> Result<T> error(@NotNull ResultCodeEnum resultCode, String message) {
        if (StrUtil.isBlank(message)) {
            return new Result<>(resultCode);
        }
        return new Result<>(resultCode.getCode(), message, null);
    }

    public static <T> Result<T> error(@NotNull Integer code, @NotNull String message) {
        return new Result<>(code, message, null);
    }
}
